using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Synchronization.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ClientDW.Synchronization.SyncESGData.CorporateDataLogic
{
    public class ComprehensiveEsgOrControversyProfilesQuery
    {
        private readonly IMongoCollection<CorporateData> corporateDataCollection;
        private readonly ILogger logger;

        public ComprehensiveEsgOrControversyProfilesQuery(IMongoCollection<CorporateData> corporateDataCollection, ILogger logger)
        {
            this.corporateDataCollection = corporateDataCollection;
            this.logger = logger;
        }

        public async Task<Dictionary<Guid, string>> GetAsync()
        {
            var stopWatch = Stopwatch.StartNew();

            var comprehensiveEsgOrControversyProfiles = await corporateDataCollection
                .Find(cd => cd.ComprehensiveEsgResearchState.ResearchState == ResearchState.ResearchAvailable || cd.ControversyResearchState.ResearchState == ResearchState.ResearchAvailable)
                .Project(cd => new CorporateData { Id = cd.Id, PeerGroup = cd.PeerGroup })
                .ToListAsync().ConfigureAwait(false);

            logger.Log($"{comprehensiveEsgOrControversyProfiles.Count} companies counted for " + $"{new StackFrame(1).GetMethod().Name} in " + $"{typeof(ComprehensiveEsgOrControversyProfilesQuery).Name} (duration {stopWatch.Elapsed})");

            return comprehensiveEsgOrControversyProfiles.ToDictionary(c => c.Id, c => c.PeerGroup);
        }
    }
}
